package com.damuzee.system.admin.web;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.util.UrlPathHelper;

import com.damuzee.core.web.session.SessionProvider;
import com.damuzee.system.admin.Constaints;
import com.damuzee.system.admin.domain.EmpUser;
import com.damuzee.system.admin.service.EmpUserService;

/**
 * 系统上下文信息拦截器
 * 拦截用户是否登录
 * 获取用户权限
 * 
 * @author karka.w
 * 2013-9-14
 *
 */

public class AdminContextInterceptor extends HandlerInterceptorAdapter {

	@Resource
	private SessionProvider session;
	@Resource
	private EmpUserService empUserService ;
	
	private boolean auth = true;
	private String[] excludeUrls;
	private String loginUrl;
	private String processUrl;
	private String returnUrl;
	
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler)
					throws Exception{
		//获取登录用户
		String userId = (String)session.getAttribute(request, Constaints.AUTH_KEY);
		EmpUser user = null ;
		if(userId != null){
			user =  new EmpUser() ;
			user.setUserName(userId);
			user = empUserService.getAdminUser(user);
		}
		
		/**设置登录成功的用户信息**/
		//RequestUtil.setUser(request, user);
		ContextThreadVariable.setUser(user);
		
		
		//不验证的请求
		String uri = getURI(request);
		if (exclude(uri)) {
			return true;
		}
		
	/*	// 用户为null跳转到登陆页面
		if (user == null) {
			response.sendRedirect(getLoginUrl(request));
			return false;
		}*/
		
		return true;
	}
	
	private String getLoginUrl(HttpServletRequest request) {
		StringBuilder buff = new StringBuilder();
		if (loginUrl.startsWith("/")) {
			String ctx = request.getContextPath();
			if (!StringUtils.isBlank(ctx)) {
				buff.append(ctx);
			}
		}
		buff.append(loginUrl);
		return buff.toString();
	}
	
	private boolean exclude(String uri) {
		if (excludeUrls != null) {
			for (String exc : excludeUrls) {
				if (exc.equals(uri)) {
					return true;
				}
			}
		}
		return false;
	}
	
	/**
	 * 获得第三个路径分隔符的位置
	 * 
	 * @param request
	 * @throws IllegalStateException
	 *             访问路径错误，没有三(四)个'/'
	 */
	private static String getURI(HttpServletRequest request)
			throws IllegalStateException {
		UrlPathHelper helper = new UrlPathHelper();
		String uri = helper.getOriginatingRequestUri(request);
		String ctxPath = helper.getOriginatingContextPath(request);
		int start = 0, i = 0, count = 1;
		if (!StringUtils.isBlank(ctxPath)) {
			count++;
		}
		while (i < count && start != -1) {
			start = uri.indexOf('/', start + 1);
			i++;
		}
		if (start <= 0) {
			throw new IllegalStateException("admin access path not like '/jeeadmin/jspgou/...' pattern: " + uri);
		}
		return uri.substring(start);
	}
	
	

	
	public boolean isAuth() {
		return auth;
	}

	public void setAuth(boolean auth) {
		this.auth = auth;
	}

	public String[] getExcludeUrls() {
		return excludeUrls;
	}

	public void setExcludeUrls(String[] excludeUrls) {
		this.excludeUrls = excludeUrls;
	}

	public String getLoginUrl() {
		return loginUrl;
	}

	public void setLoginUrl(String loginUrl) {
		this.loginUrl = loginUrl;
	}

	public String getProcessUrl() {
		return processUrl;
	}

	public void setProcessUrl(String processUrl) {
		this.processUrl = processUrl;
	}

	public String getReturnUrl() {
		return returnUrl;
	}

	public void setReturnUrl(String returnUrl) {
		this.returnUrl = returnUrl;
	}
	
	
	

}
